<script setup>
import router from '@/router';
import { onMounted, ref } from 'vue';

const user = ref({
  id: '',
  name: '',
});
const msgList = ref([
  {
    name: 'tb1326587656',
    time: '10:00 AM',
    to: 'tb1326587656',
    content: '您好，我想咨询一下这款衣服的尺码。'
  },
  {
    name: 'saler',
    time: '10:01 AM',
    to: 'customer',
    content: '您好，这款衣服有S、M、L三种尺码，您可以根据自己的身高体重选择合适的尺码。'
  },
  {
    name: 'tb1326587656',
    time: '10:02 AM',
    to: 'tb1326587656',
    content: '那我身高165cm，体重50kg，应该选哪个尺码？'
  },
  {
    name: 'saler',
    time: '10:03 AM',
    to: 'customer',
    content: '建议您选择M码，这个尺码比较适合您的身高和体重。'
  }
]);
const message = ref({
  name: '',
  time: null,
  to:'',
  content:''
})

// 定义websocket连接
let socket = null;
//初始化 WebSocket 连接
const init = () => {
  if (typeof (WebSocket) == "undefined") {
    console.log("您的浏览器不支持Websocket");
  } else {
    let socketUrl = "ws://localhost:8081/socket/" + user.value.id
    if (socket !== null) {
      console.log("socket已存在"+socket);
      socket.close()
      socket = null
    }
    //开启WebSocket服务
    socket = new WebSocket(socketUrl);
    //打开事件
    socket.onopen = function () {
    console.log("websocket已打开");
    };
    //浏览器端收消息，获取从服务端发送过来的文本消息
    socket.onmessage = function (msg) {
      // 接收消息
      console.log("收到消息：" + msg.data);
      let data = JSON.parse(msg.data)
      msgList.value.push(data)
    };
    //关闭事件
    socket.onclose = function () {
      console.log("Websocket 已关闭");
    };
    //发生错误事件
    socket.onerror = function () {
      console.log("Websocket发生了错误");
    };
  }
}
// 获取用户信息
import useUserStore from '@/store/modules/user'
const userStore = useUserStore();
onMounted(() => {
  user.value.id = userStore.id;
  user.value.name = userStore.nickname
  console.log(user.value);
  // user.value = JSON.parse(localStorage.getItem('user'))
  init()
})

const send = () => {
  // 发送消息
  if (!message.value.content) {
    console.log('请输入内容');
    return
  }
  if (typeof (WebSocket) == "undefined") {
    console.log("您的浏览器不支持Websocket");
  } else {
    message.value.from = user.value.id
    message.value.to = user.value
    message.value.time = new Date().toLocaleString()
    socket.send(JSON.stringify(message.value));
    message.value.content = ''
    // msgList.value.push(message.value)   
  }

}

</script>
<template>
  <!-- 聊天界面 -->
  <div class="message-container">
    <div class="side">
      <div class="chat-list">
        桃禧服装店
      </div>
    </div>
    <div class="chat-box">
      <p class="title">聊天界面</p>
      <div v-for="(item, index) in msgList" :key="index" class="message">
        <div class="right" v-if="item.name === 'tb1326587656'"> 
          <div class="content">{{ item.content }}</div>
          <div class="time">{{ item.time }}</div>
        </div>
        <div class="left" v-else>
          <div class="content">{{ item.content }}</div>
          <div class="time">{{ item.time }}</div>
        </div>
      </div>
      <div class="input-box">
        <el-input @keyup.enter.native="send" type="textarea" v-model="message.content" :autosize="{ minRows: 2, maxRows: 5}" placeholder="请输入聊天内容"></el-input>
        <el-button type="primary" @click="send">发送</el-button>      
      </div>
    </div>
  </div>
</template>

<style scoped lang='scss'>
.message-container{
    display: flex;
    max-width: 80vw;
    margin: 0 auto; /* 这行代码可以让容器在水平方向居中 */
    background: #fff;
    height: 800px;  
}

.chat-box {
  display: flex;
  border-radius: 5px;
  overflow: hidden;

  .title{
    font-size: 18px;
    padding: 10px;
    border-bottom:1px solid #ddd ;
    margin-bottom: 20px;
  }
}


.side {
  width: 250px;
  background-color: #f4f4f4;
  border-right: 1px solid #ddd;

  .chat-list {
    display: flex;
    align-items: center;
    padding: 10px 0;
    background-color: #fff;
    border-bottom: 1px solid #ddd;
    padding: 20px;
    font-size: 18px;
  }
}

.chat-box {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 20px;
  overflow: auto;
  position: relative;
  overflow-y: auto; /* 添加滚动条 */
  
  .message {
    display: flex;
    margin-bottom: 10px;
    justify-content: space-between;
  }
  
  .left {
    align-self: flex-start;
    margin-right: auto; /* 推到左边 */
  }

  .right {
    align-self: flex-end;
     margin-left: auto; /* 推到右边 */
  }
  
  .content {
    max-width: 500px;
    padding: 10px;
    border-radius: 10px;
    background-color: #e6f7ff;
    word-break: break-all;
  }

  .time {
    font-size: 12px;
    color: #999;
    margin-top: 5px;
  }

  
  .input-box{
    display: flex;
    position: absolute;
    bottom: 0;
    width: calc(100% - 40px);
    padding: 10px;
    
    .el-button {
      width: 80px;
      margin-left: 20px;
    }
  }
}

</style>